package com.seekting.simplewebrtc;

import android.util.Log;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

import static com.seekting.simplewebrtc.AppEnv.bAppdebug;

/**
 * Created by seekting on 17-7-27.
 */

public class AsyncPostTask {

    private final CallBack mCallBack;

    interface CallBack {
        void onSuc(String str);

        void onError();

    }

    String url;
    String body;

    public AsyncPostTask(String url, String body, CallBack c) {
        this.url = url;
        this.mCallBack = c;
        this.body = body;

    }

    public static final boolean DEBUG = bAppdebug;
    public static final String TAG = "AsyncPostTask";

    public void send() {
        OkHttpClient.Builder bu = new OkHttpClient.Builder();
        OkHttpClient k = bu.build();
        byte[] array = null;
        try {
            array = body.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final byte a[]=array;
        Call c = k.newCall(new Request.Builder()
                .addHeader("Connection", "Keep-Alive")
                .addHeader("Accept-Encoding", "identity")
                .addHeader("Content-Length",array.length+"")
                .addHeader("origin", MainActivity.URL).url(url).post(new RequestBody() {
            @Override
            public MediaType contentType() {

                MediaType media = MediaType.parse("text/plain; charset=utf-8");
                return media;
            }

                    @Override
                    public long contentLength() throws IOException {
                        return a.length;
                    }

                    @Override
            public void writeTo(BufferedSink sink) throws IOException {
                if (body != null) {
                    sink.write(a);
                }

            }
        }).build());

        c.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Log.d("seekting", "AsyncPostTask.onResponse" + str);
                mCallBack.onSuc(str);
            }
        });

    }
}
